package com.it.controller;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.domain.UserManagement;
import com.it.service.IUserManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户API管理Controller
 */
@RestController
@RequestMapping("/system/user")
public class UserManagementController {

    @Autowired
    private IUserManagementService userManagementService;

    /**
     * 查询用户API管理列表（分页）
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            UserManagement userManagement) {

        // 创建分页对象
        Page<UserManagement> page = new Page<>(pageNum, pageSize);

        // 使用LambdaQueryWrapper构建查询条件
        LambdaQueryWrapper<UserManagement> queryWrapper = new LambdaQueryWrapper<>();
        if (userManagement.getUsername() != null) {
            queryWrapper.like(UserManagement::getUsername, userManagement.getUsername());
        }
        if (userManagement.getStatus() != null) {
            queryWrapper.eq(UserManagement::getStatus, userManagement.getStatus());
        }
        if (userManagement.getEmail() != null) {
            queryWrapper.like(UserManagement::getEmail, userManagement.getEmail());
        }
        if (userManagement.getPhone() != null) {
            queryWrapper.like(UserManagement::getPhone, userManagement.getPhone());
        }
        if (userManagement.getRoleId() != null) {
            queryWrapper.eq(UserManagement::getRoleId, userManagement.getRoleId());
        }
// 密码通常不应该作为查询条件，建议前端移除
        // 可以继续添加其他条件...
        // 执行分页查询
        IPage<UserManagement> pageResult = userManagementService.page(page, queryWrapper);
        // 构建返回结果
        Map<String, Object> response = new HashMap<>();
        response.put("rows", pageResult.getRecords());
        response.put("total", pageResult.getTotal());

        return ResponseEntity.ok(response);
    }
    /**
     * 获取用户API管理详细信息
     */
    @GetMapping("/{userId}")
    public ResponseEntity<UserManagement> getInfo(@PathVariable Long userId) {
        UserManagement user = userManagementService.getById(userId);
        return ResponseEntity.ok(user);
    }

    /**
     * 新增用户API管理
     */
    @PostMapping
    public ResponseEntity<Boolean> add(@RequestBody UserManagement userManagement) {
        // 密码非空就加密
        if (userManagement.getPassword() != null && !userManagement.getPassword().isEmpty()) {
            userManagement.setPassword(MD5.create().digestHex(userManagement.getPassword()));
        }
        boolean result = userManagementService.save(userManagement);
        return ResponseEntity.ok(result);
    }

    /**
     * 修改用户API管理
     */
    @PutMapping
    public ResponseEntity<Boolean> edit(@RequestBody UserManagement userManagement) {
        // 1. 查出旧对象
        UserManagement old = userManagementService.getById(userManagement.getUserId());
        if (old == null) {
            return ResponseEntity.ok(false);
        }

        // 2. 若前端传来的密码与库中一致，则不处理；否则重新加密
        String newPwd = userManagement.getPassword();
        if (newPwd != null && !newPwd.equals(old.getPassword())) {
            userManagement.setPassword(MD5.create().digestHex(newPwd));
        }

        boolean result = userManagementService.updateById(userManagement);
        return ResponseEntity.ok(result);
    }

    /**
     * 删除用户API管理
     */
    @DeleteMapping("/{userIds}")
    public ResponseEntity<Boolean> remove(@PathVariable String userIds) {
        List<Long> idList = Arrays.stream(userIds.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());
        boolean result = userManagementService.removeByIds(idList);
        return ResponseEntity.ok(result);
    }
}